# coding=utf-8

from flask import render_template
from flask_login import login_required, current_user
from datetime import datetime, timedelta
from apscheduler.triggers.cron import CronTrigger

from app.routes.main import bp
from app.models import Dispatcher, Scheduler, Case, Project
from app.cores.dictionaries import REPORT_RESULT, ELEMENT_TYPE


@bp.route('/')
@bp.route('/index')
@login_required
def index():
    # 获取历史构建次数
    total_dispatcher_count = len(Dispatcher.query.all())
    # 获取当前用户构建次数
    total_dispatcher_count_current_user = len(Dispatcher.query.filter_by(user_id=current_user.id).all())
    # 获取最近2周构建结果数据/最近2周当前用户构建结果数据
    current_time = datetime.now()
    current_date = datetime(year=current_time.year, month=current_time.month, day=current_time.day, hour=23, minute=59,
                            second=59)
    current_date_14_days_ago = current_date - timedelta(days=14)
    dispatchers = Dispatcher.query.filter(Dispatcher.start_time > current_date_14_days_ago,
                                          Dispatcher.start_time < current_date).all()
    echart_line_last_dispatch_dataset_source = []
    echart_line_last_dispatch_current_user_dataset_source = []
    for i in range(14):
        echart_line_last_dispatch_dataset_source.append({
            'date': (current_date_14_days_ago + timedelta(days=i+1)).strftime("%Y%m%d"),
            '构建': 0, '成功': 0, '失败': 0, '错误': 0, '中止': 0,
         })
        echart_line_last_dispatch_current_user_dataset_source.append({
            'date': (current_date_14_days_ago + timedelta(days=i+1)).strftime("%Y%m%d"),
            '构建': 0, '成功': 0, '失败': 0, '错误': 0, '中止': 0,
        })
    for dispatcher in dispatchers:
        date = dispatcher.start_time.strftime("%Y%m%d")
        for source in echart_line_last_dispatch_dataset_source:
            if date == source['date']:
                source['构建'] += 1
                if dispatcher.report.result == REPORT_RESULT.SUCCESS:
                    source['成功'] += 1
                elif dispatcher.report.result == REPORT_RESULT.ERROR:
                    source['错误'] += 1
                elif dispatcher.report.result == REPORT_RESULT.FAILURE:
                    source['失败'] += 1
                elif dispatcher.report.result == REPORT_RESULT.ABORT:
                    source['中止'] += 1
        for source in echart_line_last_dispatch_current_user_dataset_source:
                if dispatcher.user_id == current_user.id and date == source['date']:
                    source['构建'] += 1
                    if dispatcher.report.result == REPORT_RESULT.SUCCESS:
                        source['成功'] += 1
                    elif dispatcher.report.result == REPORT_RESULT.ERROR:
                        source['错误'] += 1
                    elif dispatcher.report.result == REPORT_RESULT.FAILURE:
                        source['失败'] += 1
                    elif dispatcher.report.result == REPORT_RESULT.ABORT:
                        source['中止'] += 1
    # 获取正在运行的定时任务数
    # scheduler_enable_count = len(Scheduler.query.filter_by(enable=True).all())
    # 获取正在运行的定时任务信息
    schedulers = []
    date = datetime.now()
    for row in Scheduler.query.filter_by(element_type=ELEMENT_TYPE.PROJECT, enable=True).all():
        project = Project.query.filter_by(id=row.element_id).first()
        if project:
            try:
                cron_trigger = CronTrigger.from_crontab(row.cron)
                next_fire_time = cron_trigger.get_next_fire_time(None, now=date + timedelta(microseconds=1)).strftime('%Y-%m-%d %H:%M:%S')
            except Exception as e:
                next_fire_time = 'cron解析异常'
            schedulers.append(dict(id=row.element_id, name=project.name, cron=row.cron, next_fire_time=next_fire_time))
    # 获取总案例个数
    total_case_count = len(Case.query.all())
    return render_template('main/index.html',
                           schedulers=schedulers,
                           scheduler_enable_count=len(schedulers),
                           total_dispatcher_count=total_dispatcher_count,
                           total_dispatcher_count_current_user=total_dispatcher_count_current_user,
                           total_case_count=total_case_count,
                           echart_line_last_dispatch_dataset_source=echart_line_last_dispatch_dataset_source,
                           echart_line_last_dispatch_current_user_dataset_source=echart_line_last_dispatch_current_user_dataset_source)


@bp.route('/blank')
@login_required
def blank():
    return render_template('main/blank.html')
